#!/bin/sh
# This is autotest display tool, showing gathered information in
# a hopefully meaningful way.
#
# Usage: ./autotest-show [-e] [MASK]
# Use -e to display winrates in terms of Elo points.

do_elo=
if [ "$1" = -e ]; then
	do_elo=1
	shift
fi

mask="$1"
[ -n "$mask" ] || mask="*"
. ./autotest-lib

if [ ! -d "r" ]; then
	echo "Did you run autotest-gather?" >&2
	exit 1
fi

# Load rc quickly:
player() { :; }
pknown=" "
pairing() { pknown="$pknown$(pairid "$@") "; }
. ./rc

color_stale="\033[33m"
color_bad="\033[31m"
color_fresh="\033[1m"
color_stop="\033[0m"

pairing_status() {
	# See README for explanation of flags.
	error=0;
	if [ -s "r/$pairing.error" ] && [ "$(cat "r/$pairing.error")" -gt 0 ]; then
		error=1;
	fi
	known=1; [ "${pknown#* $pairing *}" != "$pknown" ] || known=0
	active=1; ([ -s "r/$pairing.beacon" ] && [ "$(cat "r/$pairing.beacon")" -ge "$(($(date +%s) - 60*60*2))" ]) || active=0
	case $error$known$active in
		001) status="${color_stale}?";;
		000) status="${color_stale}/";;
		011) status="${color_fresh}.";;
		010) status="${color_fresh}${color_bad}!";;
		1*0) status="${color_bad}x";;
		1*1) status="${color_fresh}${color_bad}X";;
	esac
}

prob2elo() {
	echo "400*l(10*$1/(1-$1))/l(10)" | bc -l
}

elo_stats() {
	ref=0.5
	refelo=$(prob2elo $ref); wrelo=$(prob2elo $winrate);
	wrelo_d=$(prob2elo "($winrate-$sd)"); wrelo_u=$(prob2elo "($winrate+$sd)")
	delo=$((${wrelo%.*}-${refelo%.*})); delo_u=$((${wrelo_u%.*}-${refelo%.*})); delo_d=$((${wrelo_d%.*}-${refelo%.*}))
	stats="$games\t$delo_d\t$delo\t$delo_u"
}

rm -f r/*.summary.dat r/*.html

if [ -n "$do_elo" ]; then
	echo -e "S GAMES\tWR -/0/+ (S.D.)\t\tPAIRING"
else
	echo -e "S GAMES\tWINRATE\tS.D.\tPAIRING"
fi
for pairing in $( (echo "$pknown" | tr ' ' '\n'; ls r/*.dat | sed 's#^r/##; s#\.dat$##') | sort | uniq); do
	[ ! -s "r/$pairing.dat" ] || $twogtp_path -analyze "r/$pairing.dat"
	pairing_status "$pairing" # sets status
	if [ -s "r/$pairing.summary.dat" ]; then
		read games winrate sd <<<$(cat "r/${pairing}".summary.dat | cut -f 1,7,8 | tail -n +2)
		if [ -n "$do_elo" ]; then
			elo_stats
		else
			stats="$games\t$winrate\t$sd"
		fi
		echo -e "$status $stats\t$pairing$color_stop"
	else
		echo -e "$status 0\t-\t-\t$pairing$color_stop"
	fi
done
